import sqlite3
from flask import render_template, request, redirect, url_for, flash, session
from . import web_bp
from models import get_all_menus, get_menu_by_id, create_operation_log, get_db_connection

# 菜单管理
@web_bp.route('/menus')
def menus():
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    menus = get_all_menus()
    return render_template('menus.html', menus=menus)

# 添加菜单
@web_bp.route('/menus/add', methods=['GET', 'POST'])
def add_menu():
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute('SELECT id, name FROM permissions')
    permissions = cursor.fetchall()
    conn.close()
    
    if request.method == 'POST':
        name = request.form['name']
        parent_id = request.form['parent_id'] if request.form['parent_id'] else 0
        icon = request.form['icon']
        path = request.form['path']
        sort_order = request.form['sort_order']
        
        conn = get_db_connection()
        cursor = conn.cursor()
        try:
            cursor.execute('INSERT INTO menus (name, parent_id, icon, path, sort_order) VALUES (?, ?, ?, ?, ?)',
                          (name, parent_id, icon, path, sort_order))
            conn.commit()
            flash('菜单添加成功')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '添加菜单', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'name: {name}', '成功', 0)
        except Exception as e:
            flash(f'菜单添加失败: {str(e)}')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '添加菜单', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'name: {name}', f'失败: {str(e)}', 0)
        finally:
            conn.close()
        
        return redirect(url_for('web.menus'))
    
    menus = get_all_menus()
    return render_template('add_menu.html', menus=menus, permissions=permissions)

# 菜单管理 - 编辑菜单
@web_bp.route('/menus/edit/<int:menu_id>', methods=['GET', 'POST'])
def edit_menu(menu_id):
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    menu = get_menu_by_id(menu_id)
    if not menu:
        flash('菜单不存在')
        # 记录操作日志
        create_operation_log(session['user_id'], session['username'], '更新菜单', 
                            'POST', request.url, request.remote_addr, 
                            request.headers.get('User-Agent'), f'menu_id: {menu_id}', '菜单不存在', 0)
        return redirect(url_for('web.menus'))
    
    all_menus = get_all_menus()
    all_permissions = []
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute('SELECT id, name FROM permissions')
    all_permissions = cursor.fetchall()
    conn.close()
    
    if request.method == 'POST':
        name = request.form['name']
        parent_id = request.form['parent_id'] if request.form['parent_id'] else 0
        icon = request.form['icon']
        path = request.form['path']
        sort_order = request.form['sort_order']
        permission_id = request.form['permission_id'] if request.form['permission_id'] else None
        
        conn = get_db_connection()
        cursor = conn.cursor()
        try:
            cursor.execute('''UPDATE menus SET name=?, parent_id=?, icon=?, path=?, sort_order=?, permission_id=? 
                             WHERE id=?''',
                          (name, parent_id, icon, path, sort_order, permission_id, menu_id))
            conn.commit()
            flash('菜单更新成功')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '更新菜单', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'menu_id: {menu_id}', '成功', 0)
        except Exception as e:
            flash(f'菜单更新失败: {str(e)}')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '更新菜单', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'menu_id: {menu_id}', f'失败: {str(e)}', 0)
        finally:
            conn.close()
        
        return redirect(url_for('web.menus'))
    
    return render_template('edit_menu.html', menu=menu, menus=all_menus, permissions=all_permissions)

# 删除菜单
@web_bp.route('/menus/delete/<int:menu_id>', methods=['POST'])
def delete_menu(menu_id):
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    conn = get_db_connection()
    cursor = conn.cursor()
    # 先获取菜单信息用于日志记录
    menu = cursor.execute('SELECT name FROM menus WHERE id=?', (menu_id,)).fetchone()
    try:
        cursor.execute('DELETE FROM menus WHERE id=?', (menu_id,))
        conn.commit()
        flash('菜单删除成功')
        # 记录操作日志
        create_operation_log(session['user_id'], session['username'], '删除菜单', 
                            'POST', request.url, request.remote_addr, 
                            request.headers.get('User-Agent'), f'menu_id: {menu_id}, name: {menu[0] if menu else "unknown"}', '成功', 0)
    except Exception as e:
        flash(f'菜单删除失败: {str(e)}')
        # 记录操作日志
        create_operation_log(session['user_id'], session['username'], '删除菜单', 
                            'POST', request.url, request.remote_addr, 
                            request.headers.get('User-Agent'), f'menu_id: {menu_id}, name: {menu[0] if menu else "unknown"}', f'失败: {str(e)}', 0)
    finally:
        conn.close()
    
    return redirect(url_for('web.menus'))